package rgs.sphere.jdbc.algorithm;

import com.google.common.collect.Range;
import org.apache.shardingsphere.api.sharding.complex.ComplexKeysShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.complex.ComplexKeysShardingValue;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @program: rgs-study0project
 * @description: 数据库精确查询分片策略
 * @author: Mr.Ren
 * @create: 2023-11-12 21:19
 **/
public class MyComplexTableAlgorithm implements ComplexKeysShardingAlgorithm<Long> {

    @Override
    public Collection<String> doSharding(Collection<String> collection, ComplexKeysShardingValue<Long> complexKeysShardingValue) {
        String logicTableName = complexKeysShardingValue.getLogicTableName();
        Range<Long> cid = complexKeysShardingValue.getColumnNameAndRangeValuesMap().get("cid");
        Collection<Long> userIds = complexKeysShardingValue.getColumnNameAndShardingValuesMap().get("userId");

        Long upper = cid.upperEndpoint();
        Long lower = cid.lowerEndpoint();

        List<String> rsp = new ArrayList<>();
        for (Long userId : userIds) {
            BigInteger bigInteger = BigInteger.valueOf(userId);
            String suffix = bigInteger.mod(new BigInteger("2")).add(new BigInteger("1")).toString();
            rsp.add(logicTableName + "_" + suffix);
        }
        return rsp;
    }
}
